package org.example.springchatroom.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.example.springchatroom.constants.Constants;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/9/3
 * Time: 15:05
 */
@Slf4j
public class JwtUtils {

    private static final long EXPIRATION_TIME = 36_000_000;
    private static final String SECRET_STRING = "jiuzhuannitianyangguangdreamjiuzhuannitianyangguangdream";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_STRING));

    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(key)
                .compact();
    }

    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析token失败, token:{}", token);
            return null;
        }
        return claims;
    }

    public static Integer getIdByToken(String token){
        Claims claims = parseToken(token);
        if(claims != null) {
            Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
            if(userId > 0){
                return userId;
            }
        }
        return null;
    }
}